package com.pay.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.pay.beans.ReturnContent;
import com.pay.common.util.PropertyUtil;
import com.pay.commons.utils.security.DigestUtils;
import com.pay.constants.MarketplanConstant;
import com.pay.constants.RetConstants;
import com.pay.dubbo.wx.EnterPrisePaymentServiceFacade;
import com.pay.util.NeedOpenId;
import com.pay.util.RequestUtil;

/**
 * @Description: 企业付款
 * @see: EnterPrisePaymentController 此处填写需要参考的类
 * @version 2016年12月27日 下午2:25:56
 * @author shulin.feng
 */
@Controller
@RequestMapping("/enterPrise")
public class EnterPrisePaymentController {

	private Logger logger = LoggerFactory.getLogger(EnterPrisePaymentController.class);

	@Resource
	private EnterPrisePaymentServiceFacade enterPrisePaymentServiceFacade;

	private static String url;// 项目路径
	private static String staticUrl;//静态资源
	private static String redirectAuth;//跳转
	private static String secretKey;//跳转
	static {
		PropertyUtil propertyUtil = PropertyUtil.getInstance("wxweb");
		redirectAuth =  propertyUtil.getProperty("com.pay.wx.redirectAuthUrl");
		url = propertyUtil.getProperty("weixin.system.url");
		staticUrl = propertyUtil.getProperty("com.pay.wx.staticResHomeUrl");
		secretKey = propertyUtil.getProperty("com.pay.wx.secretKey");
	}

	/**
	 * @Description 发送领取红包模板
	 * @param param
	 * @return
	 * @see 需要参考的类或方法
	 */
	@RequestMapping(value = "sendPayTemplate", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
	public @ResponseBody String sendPayTemplate(HttpServletRequest request,HttpServletResponse response, @RequestParam Map<String, String> param) {
		String result;
		try {
			response.setHeader("Access-Control-Allow-Origin", "*");
			if (!validateSign(param, secretKey,param.get("sign"))) {
				return JSON.toJSONString(new ReturnContent<>(RetConstants.ERROR, RetConstants.PARAM_ERROR_MSG));
			}
			// 红包模板详情地址：系统路径+请求拼接请求参数
			StringBuffer sb = new StringBuffer(redirectAuth)
								.append(url)
								.append("enterPrise/toPay&");
			String templateurl =  sb.toString();
			param.put("url", templateurl);
			logger.info("EnterPrisePaymentController/sendPayTemplate/param:{}", JSON.toJSONString(param));
			result = enterPrisePaymentServiceFacade.sendPayTemplate(param);
			logger.info("EnterPrisePaymentController/sendPayTemplate/result:{}", result);
		} catch (Exception e) {
			logger.error("发送领取红包模板异常EnterPrisePaymentController/sendPayTemplate/exception:{}", e);
			result = JSON.toJSONString(new ReturnContent<>(RetConstants.SYSTEM_ERROR, RetConstants.SYSTEM_ERROR_MSG));
		}
		return result;
	}
	
	private boolean validateSign( Map<String, String> map,String secretKey,String sign){
		String partnerString ="";
		ArrayList<String> paramNames = new ArrayList<String>(map.keySet());
		Collections.sort(paramNames);
		StringBuilder signSource = new StringBuilder();
		Iterator<String> iterator = paramNames.iterator();
		logger.info("EnterPrisePaymentController/sendPayTemplate/validateSign/param:{}", JSON.toJSONString(map));
		while (iterator.hasNext()) {
			String paramName = iterator.next();
			if (StringUtils.isNoneBlank(map.get(paramName))&&!"class".equals(paramName)&&!"sign".equals(paramName)) {
				signSource.append(paramName).append("=").append(map.get(paramName));
				if (iterator.hasNext())
					signSource.append("&");
			}else{
				map.remove(paramName);
			}
		}
		
		partnerString = signSource.toString();
		partnerString += secretKey;
		logger.info("EnterPrisePaymentController/sendPayTemplate/validateSign/partnerString:{}", partnerString);
		partnerString = DigestUtils.md5DigestAsHex(partnerString.getBytes());
		logger.info("EnterPrisePaymentController/sendPayTemplate/validateSign/Md5partnerString:{}", partnerString);
		if (null!=sign && sign.equalsIgnoreCase(partnerString)) {
			return true;
		}
		return false;
	}
	
	/**
	 * @Description 去付款页面
	 * @param request
	 * @param model
	 * @return
	 * @see 需要参考的类或方法
	 */
	@RequestMapping(value = "toPay", method = RequestMethod.GET)
	@NeedOpenId(needOpenId = true, isLoginFlag = false)
	public String toPay(HttpServletRequest request,HttpServletResponse response, Model model, @RequestParam Map<String, String> param) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		logger.info("--设备类型：{}", request.getHeader("user-agent"));
		String openId = request.getParameter("openId");//联刷openid
		logger.info("EnterPrisePaymentController/toPay/openId:{}", openId);
		String ip = RequestUtil.getIpAddr(request);
		param.put("ip", ip);
		param.put("openId", openId);
		try {
			ReturnContent<?> map = enterPrisePaymentServiceFacade.createPayBill(param);
			logger.info("EnterPrisePaymentController/sendPayTemplate/map:{}", JSON.toJSONString(map));
			model.addAttribute("desc", param.get("desc"));
			if (RetConstants.SUCCESS.equals(map.getCode())) {
				StringBuffer sBuffer = new StringBuffer(staticUrl);
				sBuffer.append("redBag/custmorRedBag.html");
				sBuffer.append("?openId=");
				sBuffer.append(openId);//联刷openid
				String datas = (String) map.getData();
				sBuffer.append("&partnerTradeNo=");
				sBuffer.append(datas.split(":")[0]);
				sBuffer.append("&amount=");
				sBuffer.append(datas.split(":")[1]);
				sBuffer.append("&isNew=true");
				return "redirect:" + sBuffer.toString();
			} else if (MarketplanConstant.PAY_SUCCESS.equals(map.getCode())) {
//				model.addAttribute("amount", param.get("amount.html"));
				StringBuffer sBuffer = new StringBuffer(staticUrl);
				sBuffer.append("redBag/custmorRedBag.html");
				sBuffer.append("?openId=");
				sBuffer.append(openId);//联刷openid
				String datas = (String) map.getData();
				sBuffer.append("&partnerTradeNo=");
				sBuffer.append(datas.split(":")[0]);
				sBuffer.append("&amount=");
				sBuffer.append(datas.split(":")[1]);
				sBuffer.append("&isNew=false");
				return "redirect:" + sBuffer.toString();
			} else {
				return "/include/error";
			}
		} catch (Exception e) {
			logger.error("跳转到去付款页面异常EnterPrisePaymentController/toPay/exception:{}", e);
			return "/include/error";
		}
	}


	/**
	 * @Description 领取企业付款
	 * @param request
	 * @param model
	 * @param params
	 * @return
	 * @see 需要参考的类或方法
	 */
	@RequestMapping(value = "payment", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	public @ResponseBody String payment(HttpServletRequest request,HttpServletResponse response, Model model,
			@RequestParam Map<String, String> params) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		String partnerTradeNo = params.get("partnerTradeNo");
		logger.info("EnterPrisePaymentController/payment/partnerTradeNo:{}", partnerTradeNo);
		if (StringUtils.isBlank(partnerTradeNo)) {
			return JSON.toJSONString(new ReturnContent<>(MarketplanConstant.NOT_EXIST_ORDERNO, "商户订单号不能为空"));
		}
		try {
			String result = enterPrisePaymentServiceFacade.payment(partnerTradeNo);
			logger.info("EnterPrisePaymentController/sendPayTemplate/result:{}", result);
			return result;
		} catch (Exception e) {
			logger.error("领取企业付款异常EnterPrisePaymentController/payment/exception:{}", e);
			return JSON.toJSONString(new ReturnContent<>(RetConstants.SYSTEM_ERROR, RetConstants.SYSTEM_ERROR_MSG));
		}
	}
}